<?php

namespace App\Http\Controllers\Admin\Service;

use App\Http\Controllers\Controller;
use App\Models\OrderModel;
use Illuminate\Http\Request;


class Dec extends Controller
{

    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $customer_name = $request->input('name', '');
        $order_sn = $request->input('sn', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');

        $query = OrderModel::query()->whereHas('customer', function($query) use ($customer_name) {
            if($customer_name){
                $query->where('name', 'like', "%{$customer_name}%");
            }
        });

        if($order_sn){
            $query->where('sn', $order_sn);
        }

        if($create_start && $create_end){
            $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'customer_name' => $item->customer->name ?? '',
                'sn' => $item->sn,
                'clearance_list' => $item->clearance_list,
                'created_at' => $item->created_at->toDateTimeString()
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

}
